<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
        <div id='box'>
            <h1>computed vs method vs watch</h1>
            <input type="text" v-model="msg">
            <span>{{msg}}</span>
            <ul>
                <li v-for="(v, i) in arr">
                    <div>
                        <p>{{v.tit}}</p>
                    </div>
                    <div>
                        <a href="javascript:" @click="red(i)">-</a>
                        <input type="text" name="" id="" v-model="v.num">
                        <a href="javascript:" @click="add(i)">+</a>
                    </div>
                    <div>
                        单价：<span>{{v.price}}</span>
                    </div>
                    <div>
                        小计：<i>{{v.price * v.num}}</i>
                    </div>
                </li>
            </ul>
            <p>合计：{{wsum}}</p>
        </div>
        

    </body>
    <script>
        new Vue({
            el: '#box',
            data(){
                return {
                    arr:[
                        {tit:"phone", num:1, price:"1000"},
                        {tit: "tv", num:2, price: "2000"},
                        {tit: "computer", num:3, price:"3000"}
                    ],
                    msg: '',
                    wsum: 0,
                    
                }
            },
            methods:{
                red(i){
                    console.log("in red");
                    if(this.arr[i].num>0) this.arr[i].num--;
                },
                add(i){
                    console.log("in add");
                    this.arr[i].num++;
                },
                res(){
                    console.log("in res");
                    let res = 0;
                    for(let i=0; i<this.arr.length; i++){
                        res += this.arr[i].num * this.arr[i].price;
                    }
                    return res;
                }
            },
            computed:{
                sum: function(){
                    console.log("in computed");
                    let res = 0;
                    for(let elem of this.arr){
                        res += elem.num * elem.price;
                    }
                    return res
                }
            },
            watch:{
                arr:{
                    handler: function(newVal, oldVal){
                        let res = 0;
                        for(let i=0; i<this.arr.length; i++){
                            res += this.arr[i].num * this.arr[i].price;
                        }
                        this.wsum = res;
                    },
                    immediate: true,
                    deep: true
                }
            }
        })
    </script>
</html>